﻿using BrnMall.Services;
using QD.PushManager.Manager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web.Http;

namespace QiDong.PC.Api.Controllers
{
    public class PageController : ApiController
    {
        /// <summary>
        /// //根据二级域名，重定向(二级域名格式：http://123.711688.org)
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult Get(int userid = 0)
        {
            var host = Request.RequestUri.Host;
            Regex r = new Regex("^([0-9]+).711688.com.cn");
            string msg = string.Empty;
            try
            {
                int dyb_userid = r.IsMatch(host) ? Convert.ToInt32(r.Match(host).Groups[1].Value) : userid;

                //获取用户名
                var userName = UserManager.GetUserName(dyb_userid);

                if (!string.IsNullOrEmpty(userName))
                {
                    //获取关联ID
                    var uid = OAuths.GetUidByOpenIdAndServer(userName, "dyb");
                    if (uid > 0)
                    {
                        //获取用户
                        var userModel = Users.GetPartUserById(uid);
                        if (userModel != null && userModel.StoreId > 0)
                        {
                            return Redirect($"http://pc.711688.co/pages/?storeid={userModel.StoreId}");
                        }
                    }

                }
            }
            catch (Exception ex) { msg = ex.Message; }

            //找不到会员,跳转到小程序首页
            var defaultUrl = $"http://www.711688.net.cn?{host}&msg={msg}&userid={userid}";
            return Redirect(defaultUrl);
        }
    }
}
